import { createStore } from 'vuex'
import axios from 'axios'
import { encrypt, decrypt, verifyPassword } from '@/utils/crypto'
import { ref } from 'vue'
import { useRouter } from 'vue-router'

const API_URL = 'http://localhost:3000'

// 创建 axios 实例
const api = axios.create({
  baseURL: API_URL,
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
api.interceptors.request.use(
  config => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
api.interceptors.response.use(
  response => response,
  error => {
    if (error.response) {
      switch (error.response.status) {
        case 401:
          // 未授权，清除用户信息并跳转到登录页
          store.dispatch('logout')
          router.push('/login')
          break
        case 403:
          // 权限不足
          store.commit('SET_ERROR', '权限不足')
          break
        case 404:
          store.commit('SET_ERROR', '请求的资源不存在')
          break
        case 500:
          store.commit('SET_ERROR', '服务器错误')
          break
        default:
          store.commit('SET_ERROR', error.response.data.message || '请求失败')
      }
    } else if (error.request) {
      store.commit('SET_ERROR', '网络错误，请检查网络连接')
    } else {
      store.commit('SET_ERROR', error.message)
    }
    return Promise.reject(error)
  }
)

// 从本地存储加载购物车
const loadCart = () => {
  try {
    const cart = localStorage.getItem('cart')
    if (!cart) return []
    return JSON.parse(cart)
  } catch (error) {
    console.error('加载购物车失败:', error)
    return []
  }
}

// 保存购物车到本地存储
const saveCart = (cart) => {
  try {
    localStorage.setItem('cart', JSON.stringify(cart))
  } catch (error) {
    console.error('保存购物车失败:', error)
  }
}

// 清除所有认证相关数据
const clearAuthData = () => {
  localStorage.removeItem('token');
  localStorage.removeItem('role');
  localStorage.removeItem('username');
  localStorage.removeItem('userId');
  localStorage.removeItem('lastRoute');
}

export default createStore({
  state: {
    user: null,
    isAuthenticated: false,
    role: null,
    medicines: [],
    cart: loadCart(),
    orders: [],
    loading: false,
    error: null,
    tokenExpiration: null
  },
  mutations: {
    SET_USER(state, user) {
      state.user = user
      state.isAuthenticated = !!user
      state.role = user ? user.role : null
      if (!user) {
        state.cart = []
        saveCart(state.cart)
      }
    },
    SET_MEDICINES(state, medicines) {
      state.medicines = medicines
    },
    SET_CART(state, cart) {
      state.cart = cart
      saveCart(state.cart)
    },
    ADD_TO_CART(state, medicine) {
      if (!state.isAuthenticated) {
        return
      }
      const existingItem = state.cart.find(item => item.id === medicine.id)
      if (existingItem) {
        existingItem.quantity += medicine.quantity || 1
      } else {
        state.cart.push({ ...medicine, quantity: medicine.quantity || 1 })
      }
      saveCart(state.cart)
    },
    REMOVE_FROM_CART(state, medicineId) {
      state.cart = state.cart.filter(item => item.id !== medicineId)
      saveCart(state.cart)
    },
    UPDATE_CART_ITEM_QUANTITY(state, { id, quantity }) {
      const item = state.cart.find(item => item.id === id)
      if (item) {
        item.quantity = quantity
        saveCart(state.cart)
      }
    },
    CLEAR_CART(state) {
      state.cart = []
      saveCart(state.cart)
    },
    SET_ORDERS(state, orders) {
      state.orders = orders
    },
    SET_LOADING(state, loading) {
      state.loading = loading
    },
    SET_TOKEN_EXPIRATION(state, expiration) {
      state.tokenExpiration = expiration
    },
    SET_ERROR(state, error) {
      state.error = error
      // 5秒后自动清除错误信息
      if (error) {
        setTimeout(() => {
          state.error = null
        }, 5000)
      }
    }
  },
  actions: {
    async login({ commit }, credentials) {
      try {
        commit('SET_LOADING', true)
        commit('SET_ERROR', null)
        
        const response = await api.get('/users')
        const users = response.data
        
        const user = users.find(u => u.username === credentials.username)
        if (!user) {
          throw new Error('用户名或密码错误')
        }
        
        const isValid = await verifyPassword(credentials.password, user.password)
        if (!isValid) {
          throw new Error('用户名或密码错误')
        }
        
        // 创建token数据
        const tokenData = {
          id: user.id,
          username: user.username,
          role: user.role,
          exp: Date.now() + 24 * 60 * 60 * 1000 // 24小时过期
        }
        
        const token = encrypt(tokenData)
        
        // 设置用户状态
        commit('SET_USER', {
          id: user.id,
          username: user.username,
          role: user.role
        })
        commit('SET_TOKEN_EXPIRATION', tokenData.exp)
        
        // 保存认证信息
        localStorage.setItem('token', token)
        localStorage.setItem('role', user.role)
        localStorage.setItem('username', user.username)
        localStorage.setItem('userId', user.id)
        localStorage.setItem('tokenExpiration', tokenData.exp)
        
        return user
      } catch (error) {
        commit('SET_ERROR', error.message)
        throw error
      } finally {
        commit('SET_LOADING', false)
      }
    },
    
    async refreshToken({ commit, state }) {
      try {
        const token = localStorage.getItem('token')
        if (!token) return null
        
        const tokenData = decrypt(token)
        if (!tokenData || !tokenData.exp) return null
        
        // 如果token还有超过1小时的有效期，不需要刷新
        if (tokenData.exp - Date.now() > 60 * 60 * 1000) {
          return token
        }
        
        // 创建新的token
        const newTokenData = {
          ...tokenData,
          exp: Date.now() + 24 * 60 * 60 * 1000
        }
        
        const newToken = encrypt(newTokenData)
        localStorage.setItem('token', newToken)
        localStorage.setItem('tokenExpiration', newTokenData.exp)
        commit('SET_TOKEN_EXPIRATION', newTokenData.exp)
        
        return newToken
      } catch (error) {
        console.error('刷新token失败:', error)
        return null
      }
    },
    
    logout({ commit }) {
      clearAuthData()
      commit('SET_USER', null)
      commit('SET_TOKEN_EXPIRATION', null)
      commit('CLEAR_CART')
    },
    
    async fetchMedicines({ commit }) {
      try {
        commit('SET_LOADING', true)
        commit('SET_ERROR', null)
        
        const response = await api.get('/medicines')
        commit('SET_MEDICINES', response.data)
      } catch (error) {
        commit('SET_ERROR', error.message)
        throw error
      } finally {
        commit('SET_LOADING', false)
      }
    },
    async createOrder({ commit, state }, orderData) {
      try {
        commit('SET_LOADING', true)
        commit('SET_ERROR', null)
        
        const order = {
          userId: state.user.id,
          items: state.cart,
          shipping: orderData.shipping || 10,
          total: (state.cart.reduce((sum, item) => sum + item.price * item.quantity, 0) + (orderData.shipping || 10)),
          status: 'pending',
          paymentMethod: orderData.paymentMethod,
          shippingAddress: orderData.shippingAddress,
          createdAt: new Date().toISOString() // 使用当前日期而不是未来日期
        }
        
        const response = await api.post('/orders', order)
        // 扣减库存
        for (const item of state.cart) {
          // 获取最新的商品库存
          const medicineRes = await api.get(`/medicines/${item.id}`)
          const currentStock = medicineRes.data.stock || 0
          const newStock = currentStock - item.quantity
          await api.patch(`/medicines/${item.id}`, { stock: newStock < 0 ? 0 : newStock })
        }
        commit('CLEAR_CART')
        return response.data
      } catch (error) {
        commit('SET_ERROR', error.message)
        throw error
      } finally {
        commit('SET_LOADING', false)
      }
    },
    async fetchOrders({ commit, state }) {
      try {
        commit('SET_LOADING', true)
        commit('SET_ERROR', null)
        
        const userId = state.user.id
        const response = await api.get(`/orders?userId=${userId}`)
        commit('SET_ORDERS', response.data)
      } catch (error) {
        commit('SET_ERROR', error.message)
        throw error
      } finally {
        commit('SET_LOADING', false)
      }
    },
    async fetchAllOrders({ commit }) {
      try {
        commit('SET_LOADING', true)
        commit('SET_ERROR', null)
        
        const response = await api.get('/orders')
        commit('SET_ORDERS', response.data)
      } catch (error) {
        commit('SET_ERROR', error.message)
        throw error
      } finally {
        commit('SET_LOADING', false)
      }
    },
    initializeAuth({ commit }) {
      try {
        console.log('开始初始化认证状态...');
        
        // 尝试从localStorage恢复用户信息
        const token = localStorage.getItem('token');
        const userId = localStorage.getItem('userId');
        const username = localStorage.getItem('username');
        const role = localStorage.getItem('role');
        
        // 如果localStorage中已经有用户ID、用户名和角色，可以直接恢复用户状态
        // 这样即使token有问题，也能保持登录状态
        if (userId && username && role) {
          console.log('从localStorage直接恢复用户状态:', username, role);
          
          const user = {
            id: userId,
            username: username,
            role: role
          };
          
          commit('SET_USER', user);
          
          // 然后尝试解析token以验证
          if (token) {
            try {
              // 清理可能存在的无效引号
              let cleanToken = token;
              if (token.startsWith('"') && token.endsWith('"')) {
                try {
                  cleanToken = JSON.parse(token);
                  console.log('清理了token中的引号');
                } catch (e) {
                  // 继续使用原始token
                }
              }
              
              const userData = decrypt(cleanToken);
              
              if (userData && userData.exp > Date.now()) {
                console.log('Token验证成功，用户认证有效');
              } else if (userData) {
                // token已过期但我们已经恢复了用户状态，尝试刷新token
                console.warn('Token已过期，尝试刷新');
                
                // 创建新的token
                const newTokenData = {
                  id: userId,
                  username: username,
                  role: role,
                  exp: Date.now() + 24 * 60 * 60 * 1000 // 延长24小时
                };
                
                const newToken = encrypt(newTokenData);
                localStorage.setItem('token', newToken);
                console.log('已刷新Token');
              }
            } catch (tokenError) {
              console.warn('Token解析失败，但用户状态已恢复:', tokenError);
            }
          } else {
            // 没有token但有用户信息，创建新token
            console.log('缺少token，创建新token');
            const newTokenData = {
              id: userId,
              username: username,
              role: role,
              exp: Date.now() + 24 * 60 * 60 * 1000 // 24小时
            };
            
            const newToken = encrypt(newTokenData);
            localStorage.setItem('token', newToken);
          }
          
          // 同步购物车
          const cart = loadCart();
          if (cart.length > 0) {
            commit('SET_CART', cart);
          }
          
          return user;
        }
        // 没有足够的用户信息，尝试从token恢复
        else if (token) {
          try {
            console.log('尝试从token恢复用户信息...');
            
            // 清理token格式
            let cleanToken = token;
            if (token.startsWith('"') && token.endsWith('"')) {
              try {
                cleanToken = JSON.parse(token);
              } catch (e) {
                // 继续使用原始token
              }
            }
            
            const userData = decrypt(cleanToken);
            
            if (!userData) {
              console.warn('token解密失败，清除认证信息');
              clearAuthData();
              commit('SET_USER', null);
              return null;
            }
            
            if (userData.exp > Date.now()) {
              const user = {
                id: userData.id,
                username: userData.username,
                role: userData.role
              };
              
              console.log('从token恢复用户状态成功:', user.username, user.role);
              
              commit('SET_USER', user);
              
              // 确保localStorage中有完整的用户信息
              localStorage.setItem('username', user.username || '');
              localStorage.setItem('userId', user.id || '');
              localStorage.setItem('role', user.role || '');
              
              // 同步购物车
              const cart = loadCart();
              if (cart.length > 0) {
                commit('SET_CART', cart);
              }
              
              return user;
            } else {
              console.warn('Token已过期');
              clearAuthData();
              commit('SET_USER', null);
            }
          } catch (decryptError) {
            console.error('Token解密失败:', decryptError);
            clearAuthData();
            commit('SET_USER', null);
          }
        } else {
          console.log('未找到登录信息，用户未登录');
        }
        
        return null;
      } catch (error) {
        console.error('初始化认证失败:', error);
        clearAuthData();
        commit('SET_USER', null);
        return null;
      }
    },
    
    // 辅助函数：清除所有认证相关数据
    clearAuthData({ commit }) {
      // 调用辅助函数清除localStorage
      clearAuthData();
      
      // 清除状态
      commit('SET_USER', null);
      commit('CLEAR_CART');
    },
    syncCartFromLocalStorage({ commit }) {
      try {
        const cart = loadCart()
        if (cart.length > 0) {
          // 更新存储中的购物车到Vuex状态
          commit('SET_CART', cart)
        }
      } catch (error) {
        console.error('同步购物车失败:', error)
      }
    }
  },
  getters: {
    isAuthenticated: state => !!state.user,
    isAdmin: state => state.role === 'admin',
    currentUser: state => state.user,
    cartTotal: state => state.cart.reduce((sum, item) => sum + item.price * item.quantity, 0),
    cartItemCount: state => state.cart.reduce((sum, item) => sum + item.quantity, 0),
    isLoading: state => state.loading,
    error: state => state.error,
    isTokenExpired: state => {
      if (!state.tokenExpiration) return true
      return Date.now() >= state.tokenExpiration
    }
  }
}) 